﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.UserRoleCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Impl;
using RBAC_Uthorization.Infrstructre.Interface;
using System.Transactions;

namespace RBAC_Uthorization.API.Application.CommandHandlers.UserRoleHandler
{
    public class UserRoleCreateCommandHandlers : IRequestHandler<UserRoleCreateCommand, ApiResult<int>>
    {
        private readonly ILogger<UserRoleCreateCommandHandlers> _logger;
        private readonly IUserRoleRepository _UserRoleRepository;
        public UserRoleCreateCommandHandlers(ILogger<UserRoleCreateCommandHandlers> logger,IUserRoleRepository userRoleRepository)
        {
            _logger = logger;
            _UserRoleRepository = userRoleRepository;
        }

        public async Task<ApiResult<int>> Handle(UserRoleCreateCommand request, CancellationToken cancellationToken)
        {
            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                  
                    foreach (var userId in request.dto.UserId)
                    {
                        var userRole = new sys_user_role
                        {
                            user_id = userId,
                            role_id = request.dto.RoleId,
                            create_by=request.createName
                            
                        };
                        await _UserRoleRepository.AddAsync(userRole);
                    }

                    transaction.Complete();
                    return new ApiResult<int>();
                }
                
                catch (Exception ex)
                {
                    //发生异常，事务回滚

                    transaction.Dispose();
                    _logger.LogError(ex, $"为RoleId添加用户角色时发生错误：{request.dto.RoleId}");
                    throw;

                }
            }
        }
    }
}
